package com.anzym.android.kegdroiddisplay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;

public class KegDroidDisplayActivity extends Activity {
	
	private String TAG = "KegDroidDisplayActivity";
	
	private static String dataUrl = "http://anzymtest.appspot.com/kegdroids?v=all";
	
	static final int OZ_PER_GAL = 128;
	KegDroidMapFragment kdMapFrag;
	private KegDroidStatsFragment kdStatsFrag;
	private JSONObject kegInfo;
	private static int NUMKEGDROIDS = 3;
	
	/*
	 * KegDroid Ids.
	 */
	private static String kegDroidNumbers[] = {"0", "f4fc9ea06a17c90c", "fe4a6778fd54a25e", "fe4a6778fd54a25e"};

	/*
	 *   KegDroidData[0] is reserved for global data
	 */
	private static KegDroidData mKegDroidData[] = new KegDroidData[NUMKEGDROIDS + 1];
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new Random(1000);
        
        for (int i = 0; i < mKegDroidData.length; i ++) {
        	mKegDroidData[i] = new KegDroidData(kegDroidNumbers[i]);
        }
        
        FragmentManager fragMan = this.getFragmentManager();
        FragmentTransaction fragTrans = fragMan.beginTransaction();
        
        kdMapFrag = new KegDroidMapFragment();
        fragTrans.replace(R.id.map_container, kdMapFrag);
        
        kdStatsFrag = new KegDroidStatsFragment(mKegDroidData);
        fragTrans.replace(R.id.stats_container, kdStatsFrag);
        
        fragTrans.commit();
        
        Log.d(TAG,"Initializing KegDroidData");
        try {
			updateKegDroidData();
		} catch (JSONException e) {}
        
        Thread myThread = null;
        Runnable runnable = new KegDroidDisplayRunner();
        myThread = new Thread(runnable);
        myThread.start();
        
    }
    
    class KegDroidDisplayRunner implements Runnable {
    	public void run() {
    		while (!Thread.currentThread().isInterrupted()) {
    			try {
    				//Log.d(TAG,"Calling updateKegDroidData Method");
    				updateKegDroidData();
    				//Log.d(TAG,"Sending kegDroidData");
    				for (int kd = 0; kd < mKegDroidData.length; kd++) {
    					//Update MAP View HERE
    					//Log.d(TAG, "kd= " + kd);
    					if (kd == 0) {
    						kdMapFrag.resetDroids();
    					} else {
    						//<TODO> Set this to activate droid by ID
    						kdMapFrag.setActiveDroid(kd);
    					}
    					kdStatsFrag.updateStats(kd);
    					Thread.sleep(5000);
    				}
    				
    			} catch (Exception e) {}
    		}
    	}
    }
    
    public void fetchData(String url) {
    	KegDroidData kdData;
    	
    	String result = "{}";
    	HttpClient httpClient = new DefaultHttpClient();
    	HttpGet httpget = new HttpGet(url);
    	HttpResponse response;
    	try {
    		response = httpClient.execute(httpget);
    		HttpEntity entity = response.getEntity();
    		if (entity != null) {
    			InputStream instream = entity.getContent();
    			result = convertStreamToString(instream);
    			instream.close();
    		}
    		kegInfo = new JSONObject(result);
    		
    		JSONArray kegDroidArray = kegInfo.getJSONArray("keg_droids");
    		Log.d(TAG, "ArrayLength: " + kegDroidArray.length());
    		
    		for (int kdi = 0; kdi < kegDroidArray.length(); kdi++ ) {
    			String kdId = kegDroidArray.getJSONObject(kdi).getString("id");
    			Log.d(TAG, "kegID: " + kdId);
    			kdData = new KegDroidData(kdId);
    			kdData.setDroidName(kegDroidArray.getJSONObject(kdi).getString("name"));
    			Log.d(TAG, "DroidName: " + kdData.getDroidName());
    			
    			String numBeers = kegDroidArray.getJSONObject(kdi).getString("total_quantity_poured");
    			Log.d(TAG, "numbBeers: " + numBeers);
    			if (!numBeers.equals("")) {    				
    				kdData.setNumBeersServed(Integer.parseInt(numBeers));
    			}

        		String numberOzPoured = kegDroidArray.getJSONObject(kdi).getString("total_volume_poured");
        		Log.d(TAG, "numOzPoured: " + numberOzPoured);
        		if (!numberOzPoured.equals("")) {
        			double gallons = (double)Integer.parseInt(numberOzPoured)/OZ_PER_GAL;
            		kdData.setNumGallonsServed(gallons);
        		}
        		
        		
        		for (int kd = 0; kd <= NUMKEGDROIDS; kd++) {
        			if (mKegDroidData[kd].getDroidId().equals(kdData.getDroidId())) {
        				Log.d(TAG, "MATCHED");
        				mKegDroidData[kd] = kdData;
        			}
        		}
    		}
    		
    		
    	
    		
    	} catch (Exception e) {
    		Log.e(TAG, "fetchData exeception " + e);
    	}
    }
    
    public void updateKegDroidData() throws JSONException {
    	//Fetch data from back end.
    	
    	fetchData(dataUrl);
    }
    
    private String convertStreamToString(InputStream is) {
	    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	    StringBuilder sb = new StringBuilder();
	    String line = null;
	    try {
	        while ((line = reader.readLine()) != null) {
	            sb.append(line + "\n");
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    } finally {
	        try {
	            is.close();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	    return sb.toString();
	}
}